<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class News extends MY_Controller {
	
	private $feedUrls = array();
	private $podcastUrls = array();

	function News() {
        
		parent::MY_Controller();

		$cache_loc = BASEPATH."cache";
		$this->load->library('simplepie');
		$this->simplepie->set_cache_location($cache_loc);

		// get Links
		$sql = "SELECT name, val FROM ".$this->tblc." WHERE name LIKE ? LIMIT 1";

		$query = $this->db->query($sql, array("feeds"));
		$res = $query->result();
		if (count($res) > 0) {
			$this->feedUrls = json_decode($res[0]->val);
		}
		$query = $this->db->query($sql, array("podcasts"));
		$res = $query->result();
		if (count($res) > 0) {
			$this->podcastUrls = json_decode($res[0]->val);
		}
	}
	
	function index() {

		$data = $this->getData('news');

		$feeds = array();
		foreach ($this->feedUrls as $url) {
			$feeds[] = $this->getFeed($url, 3);	
		}

		$data['feeds']    = $feeds;
		
		$data ['content'] = $this->load->view('news', $data, true);

		$this->load->view('layout', $data);
	}
	
	
	function podcasts() {

		$podcasts = array();
		foreach ($this->podcastUrls as $url) {
			$podcasts[] = $this->getFeed($url, 2, true);	
		}

		$data['title'] = 'Ausgewählte Podcasts zum Thema Bundesliga';
		$data['link'] = "http://kozianka-online.de/tippspiel/";
		$data['podcasts'] = $podcasts;
		header("Content-type: text/xml");
		$this->load->view('smil', $data);		
	}	

	private function getFeed($url, $count = 5, $isEncl = false) {
		$this->simplepie->set_feed_url($url);
		$this->simplepie->init();
		$this->simplepie->handle_content_type();
		$items = array();
		$count = $this->simplepie->get_item_quantity($count);
	
    for ($i=0; $i < $count; $i++) {
		$item = $this->simplepie->get_item($i);


		$itemToSave = array(
	        "link" => $item->get_permalink(),
	        "title" => $item->get_title(),
			"date" => $item->get_date('j M Y'),
			"desc" => $item->get_description()   
    	);
    	
		if ($isEncl && $item->get_enclosure() !== null) {
			$itemToSave['link'] = $item->get_enclosure()->get_link();
		}
		$items[] = $itemToSave;
    
    }
    
	$feedArr = array (
		"title" => $this->simplepie->get_title(),
		"link" => $this->simplepie->get_link(),
		"items" => $items	
	);
	return $feedArr;
}
	
}
?>